<template>
  <div class="purchaseRec-contain">
    <div class="search">
      <el-date-picker
        v-model="changeDate"
        type="daterange"
        range-separator="-"
        unlink-panels
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
        format="yyyy-MM-dd"
        @click.native="openPicker"
      />
      <el-input
        v-model="vagueKey"
        placeholder="本位码/商品名称/条码/包装规格"
        style="width: 235px"
      />
      <el-input
        v-model="businessName"
        placeholder="供应商"
      />
      <el-select
        v-model="categoriesLabel"
        placeholder="商品类别"
        multiple
        collapse-tags
        @change="changeSelect"
      >
        <!--          <el-checkbox style="height: 34px;padding-top: 10px;padding-left: 20px" v-model="checked" @change="selectAll">全选</el-checkbox>-->
        <el-option :value="categoryValue" style="height: auto">
          <el-tree
            ref="tree"
            :data="options"
            show-checkbox
            node-key="id"
            @check-change="handleTreeSelect"
          />
        </el-option>
      </el-select>
      <el-button style="margin-left: 10px; color: white; background-color: dodgerblue" @click="getTableData">搜索</el-button>
      <el-button style="color: white; background-color: lightseagreen" @click="directReport">直接上报药监</el-button>
      <el-upload :action="actionUp" :http-request="uploadFile" :before-upload="beforeFile" :show-file-list="false" accept=".xls" style="width: 155px; display: inline-block; margin: 10px">
        <el-button style="color: white; background-color: dodgerblue">上传文件上报药监</el-button>
      </el-upload>
      <el-button style="color: white; background-color: dodgerblue" @click="exportFile">导出</el-button>
    </div>
    <div class="table">
      <el-table
        tooltip-effect="dark"
        style="width: 100%;"
        height="calc(100vh - 330px)"
        :data="list"
      >
        <el-table-column width="50" label="序号" type="index" />
        <el-table-column width="150" label="采购入库单号" prop="billCode" />
        <el-table-column width="110" label="入库日期" prop="dates" />
        <el-table-column width="170" label="供应商" prop="businessName" />
        <el-table-column width="120" label="入库验收员名称" prop="staffName" />
        <el-table-column width="140" label="本位码" prop="benWM" />
        <el-table-column label="包装规格" prop="goodsSpecYj" />
        <el-table-column v-if="showCode" width="150" label="药监编码" prop="elecGoodsCode" />
        <el-table-column width="150" label="批准文号" prop="approvalNo" />
        <el-table-column width="150" label="条码" prop="barCode" />
        <el-table-column width="200" label="商品名称" prop="goodsName" />
        <el-table-column width="130" label="平台规格" prop="goodsSpec" />
        <el-table-column width="190" label="生产厂家" prop="manufacturer" />
        <el-table-column label="计量单位" prop="unit" />
        <el-table-column label="数量" prop="num" />
        <el-table-column label="批次号" prop="batchCode" />
        <el-table-column width="110" label="生产日期" prop="produceDate" />
        <el-table-column width="110" label="有效期至" prop="valDate" />
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        :current-page.sync="pageNo"
        layout="total,prev, pager, next, sizes,jumper"
        :total="totalRecord"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :page-size="10"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script>
import { getSelectOptions, getSearchList, directReport, uploadYjj, exportFile, uploadFile } from '@/api/upload'
import { getElecType } from '@/api/login'
import socket from '@/socket'

export default {
  name: 'PurchaseRec',
  data() {
    return {
      actionUp: 'aaa',
      list: [],
      pageNo: 1,
      pageSize: 10,
      businessName: '',
      endDate: '',
      startDate: '',
      vagueKey: '',
      categories: [],
      changeDate: '',
      options: [],
      totalRecord: 0,
      // totalPage: 0,
      loading: false,
      checked: false,
      categoryValue: [],
      categoriesLabel: [],
      elecType: {},
      showCode: false
    }
  },
  watch: {
    changeDate(time) {
      if (!time) {
        this.startDate = ''
        this.endDate = ''
      } else {
        this.startDate = time[0]
        this.endDate = time[1]
      }
    }
  },
  created() {
    this.getTableData()
    this.setCategory()
    getElecType().then(result => {
      this.elecType = result.data
      if (this.elecType.elecTypeValue.indexOf('市药监') >= 0) {
        this.showCode = true
      }
    }).catch(err => {
      console.log(err)
    })
  },
  methods: {
    handleCurrentChange(val) {
      this.pageNo = val
      this.getTableData('page')
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getTableData()
    },
    openPicker() {
      if (this.startDate !== '' && this.endDate !== '') {
        return
      }
      const date = new Date()
      date.setDate(1)
      const laterDate = new Date()
      this.changeDate = [date, laterDate]
    },
    changeSelect(e) {
      var arrNew = []
      var dataLength = this.categoryValue.length
      var eleng = e.length
      for (let i = 0; i < dataLength; i++) {
        for (let j = 0; j < eleng; j++) {
          if (e[j] === this.categoryValue[i].label) {
            arrNew.push(this.categoryValue[i])
          }
        }
      }
      this.$refs.tree.setCheckedNodes(arrNew)
    },
    selectAll(val) {
      if (this.checked === true) {
        this.$refs.tree.setCheckedNodes(this.options)
      } else {
        this.categories = []
        this.$refs.tree.setCheckedKeys([])
      }
    },
    handleTreeSelect(val) {
      var arr1 = []
      var arr2 = []
      var arr3 = []
      var res = this.$refs.tree.getCheckedNodes(false, false)
      res.forEach((item) => {
        arr1.push(item.label)
        arr2.push(item)
        arr3.push(item.id)
      })
      this.checked = res.length === this.options.length
      this.categoryValue = arr2
      this.categoriesLabel = arr1
      this.categories = arr3
    },
    getTreeData(data) {
      const newArr = []
      for (let i = 0; i < data.length; i++) {
        const obj = {}
        obj.label = data[i].catName
        obj.id = data[i].catCode
        obj.children = data[i].isChild === 'N' ? this.getTreeData(data[i].categoryDTOList) : null
        newArr.push(obj)
      }
      return newArr
    },
    setCategory() {
      getSelectOptions({}).then(res => {
        const options = this.getTreeData(res.data)
        this.options = options
      })
        .finally(_ => {
          this.loading = false
        })
    },
    getTableData(key) {
      const params = {
        pageNo: key === 'page' ? this.pageNo : 1,
        pageSize: this.pageSize,
        businessName: this.businessName,
        startDate: typeof this.startDate === 'object' ? this.startDate.getFullYear() + '' + '-' + ((this.startDate.getMonth() + 1) < 10 ? '0' + (this.startDate.getMonth() + 1) + '' : (this.startDate.getMonth() + 1)) +
          '-' + (this.startDate.getDate() < 10 ? '0' + this.startDate.getDate() + '' : this.startDate.getDate()) : this.startDate,
        endDate: typeof this.endDate === 'object' ? this.endDate.getFullYear() + '' + '-' + ((this.endDate.getMonth() + 1) < 10 ? '0' + (this.endDate.getMonth() + 1) + '' : (this.endDate.getMonth() + 1)) +
          '-' + (this.endDate.getDate() < 10 ? '0' + this.endDate.getDate() + '' : this.endDate.getDate()) : this.endDate,
        vagueKey: this.vagueKey,
        categories: this.categories
      }
      getSearchList({ ...params }).then(res => {
        if (key === 'page') {
          this.list = res.data.results
          this.pageSize = res.data.pageSize
          this.totalPage = res.data.totalPage
          this.totalRecord = res.data.totalRecord
        } else {
          this.list = res.data.results
          this.pageNo = res.data.page
          this.pageSize = res.data.pageSize
          this.totalPage = res.data.totalPage
          this.totalRecord = res.data.totalRecord
        }
      })
        .finally(_ => {
          this.loading = false
        })
    },
    directReport() {
      var conf = confirm('确定上传？')
      if (conf) {
        const params = {
          businessName: this.businessName,
          endDate: typeof this.endDate === 'object' ? this.endDate.getFullYear() + '' + '-' + ((this.endDate.getMonth() + 1) < 10 ? '0' + (this.endDate.getMonth() + 1) + '' : (this.endDate.getMonth() + 1)) +
            '-' + (this.endDate.getDate() < 10 ? '0' + this.endDate.getDate() + '' : this.endDate.getDate()) : this.endDate,
          categories: this.categories,
          startDate: typeof this.startDate === 'object' ? this.startDate.getFullYear() + '' + '-' + ((this.startDate.getMonth() + 1) < 10 ? '0' + (this.startDate.getMonth() + 1) + '' : (this.startDate.getMonth() + 1)) +
            '-' + (this.startDate.getDate() < 10 ? '0' + this.startDate.getDate() + '' : this.startDate.getDate()) : this.startDate,
          vagueKey: this.vagueKey
        }
        directReport({ ...params }).then(res => {
          const blob = new Blob([res.data], { type: 'text/xml;charset=utf-8' })
          const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
          const reg = /^["](.*)["]$/g
          const contentDisposition = res.headers['content-disposition']
          const result = patt.exec(contentDisposition)
          const filename = result ? result[1] : ''
          // 上传至药监
          const fileName1 = decodeURI(filename.replace(reg, '$1')).split('.')[0] + '.xml'
          let File = window.File
          try {
            new File([], '')
          } catch (e) {
            File = class File extends Blob {
              constructor(chunks, filename, opts = {}) {
                super(chunks, opts)
                this.lastModifiedDate = new Date()
                this.lastModified = this.lastModifiedDate.getTime()
                this.name = filename
              }
            }
          }
          const signFile = new File([blob], fileName1)
          if (this.elecType.elecTypeValue.indexOf('市药监') !== -1) { // 上传市药监
            if (socket.getReadyState() !== 1) {
              this.$store.dispatch('message/SetMsgInfo', {
                type: 'error',
                msg: '请安装插件上传'
              })
            } else {
              socket.send({ methonId: '5', uploadType: '3' })
              socket.send({ file: signFile, type: 'upload' })
            }
          } else { // 上传省药监
            uploadYjj({
              signFile,
              resType: 'json'
            }).then(response => {
              if (response.resultCode === 0) {
                this.$store.dispatch('message/SetMsgInfo', {
                  type: 'success',
                  msg: '上传成功'
                })
              } else {
                this.$store.dispatch('message/SetMsgInfo', {
                  type: 'error',
                  msg: response.resultText
                })
              }
            }).catch(err => {
              this.$store.dispatch('message/SetMsgInfo', {
                type: 'error',
                msg: err.message
              })
            })
          }
        }).finally(_ => {
          this.loading = false
        })
      }
    },
    exportFile() {
      const params = {
        businessName: this.businessName,
        endDate: typeof this.endDate === 'object' ? this.endDate.getFullYear() + '' + '-' + ((this.endDate.getMonth() + 1) < 10 ? '0' + (this.endDate.getMonth() + 1) + '' : (this.endDate.getMonth() + 1)) +
          '-' + (this.endDate.getDate() < 10 ? '0' + this.endDate.getDate() + '' : this.endDate.getDate()) : this.endDate,
        categories: this.categories,
        startDate: typeof this.startDate === 'object' ? this.startDate.getFullYear() + '' + '-' + ((this.startDate.getMonth() + 1) < 10 ? '0' + (this.startDate.getMonth() + 1) + '' : (this.startDate.getMonth() + 1)) +
          '-' + (this.startDate.getDate() < 10 ? '0' + this.startDate.getDate() + '' : this.startDate.getDate()) : this.startDate,
        vagueKey: this.vagueKey
      }
      exportFile({ ...params }).then(res => {
        const blob = new Blob([res.data], { type: 'application/xml;charset=utf-8' })
        const href = window.URL.createObjectURL(blob)

        if (window.navigator.msSaveBlob) {
          try {
            const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
            const reg = /^["](.*)["]$/g
            const contentDisposition = res.headers['content-disposition']
            const result = patt.exec(contentDisposition)
            const filename = result[1]
            window.navigator.msSaveBlob(blob, decodeURI(filename.replace(reg, '$1')))
          } catch (e) {
            console.log(e)
          }
        } else {
          const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
          const reg = /^["](.*)["]$/g
          const contentDisposition = res.headers['content-disposition']
          const result = patt.exec(contentDisposition)
          const filename = result[1]
          const downloadElement = document.createElement('a')

          downloadElement.download = decodeURI(filename.replace(reg, '$1'))
          downloadElement.style.display = 'none'
          downloadElement.href = href
          document.body.appendChild(downloadElement)
          downloadElement.click()

          document.body.removeChild(downloadElement)
          window.URL.revokeObjectURL(href)
        }
      }).finally(_ => {
        this.loading = false
      })
    },
    beforeFile(file) {
      const name = file.name
      const type = name.substring(name.lastIndexOf('.') + 1)
      if (type !== 'xls') {
        this.$store.dispatch('message/SetMsgInfo', {
          type: 'error',
          msg: '请上传excel文件格式'
        })
        return false
      }
    },
    uploadFile(content) {
      const params = {
        signFile: content.file
      }
      uploadFile({ ...params }).then(res => {
        const blob = new Blob([res.data], { type: 'text/xml;charset=utf-8' })
        const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
        const reg = /^["](.*)["]$/g
        const contentDisposition = res.headers['content-disposition']
        const result = patt.exec(contentDisposition)
        const filename = result[1]
        const fileName1 = decodeURI(filename.replace(reg, '$1')).split('.')[0] + '.xml'
        let File = window.File

        try {
          new File([], '')
        } catch (e) {
          File = class File extends Blob {
            constructor(chunks, filename, opts = {}) {
              super(chunks, opts)
              this.lastModifiedDate = new Date()
              this.lastModified = this.lastModifiedDate.getTime()
              this.name = filename
            }
          }
        }
        const signFile = new File([blob], fileName1)
        if (this.elecType.elecTypeValue.indexOf('市药监') !== -1) {
          if (socket.getReadyState() !== 1) {
            this.$store.dispatch('message/SetMsgInfo', {
              type: 'error',
              msg: '请安装插件上传'
            })
          } else {
            socket.send({ methonId: '5', uploadType: '3' })
            socket.send({ file: signFile, type: 'upload' })
          }
        } else {
          // 上传至药监
          uploadYjj({
            signFile,
            resType: 'json'
          }).then(response => {
            if (response.resultCode === 0) {
              this.$store.dispatch('message/SetMsgInfo', {
                type: 'success',
                msg: '上传成功'
              })
            } else {
              this.$store.dispatch('message/SetMsgInfo', {
                type: 'error',
                msg: response.resultText
              })
            }
          }).catch(err => {
            this.$store.dispatch('message/SetMsgInfo', {
              type: 'error',
              msg: err.message
            })
          })
        }
      }).finally(_ => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import '~@/style/drugAdmin/upload/drugUpload.scss';
</style>
